<template>
    <div class="app-container">
        <levelbar></levelbar>
        <div class="form-box" v-loading='loading'>
            <div class="form-title">收费设置</div>
            <el-form :model="priceSetting" :rules="priceSettingRules" ref="priceSetting" label-width="81px" class="form" label-position='right'>
                <div class="form-item">
                    <div class="form-item-title">
                        <span class="title-level">价格设置</span>
                    </div>
                    <el-row class="form-content">
                        <el-col :span="20">
                            <div v-for='(site,index) in priceSetting.priceSettingList' :key="index">
                                <el-row :gutter="21">
                                    <el-col :span='8' class='isUpdataPb'>
                                        <el-form-item label="月份" label-width="53px" :prop="'priceSettingList.' + index + '.value'" :rules="[{required: true, message: '请选择月份', trigger: 'blur'}]">
                                            <el-select ref="sel2" v-model="site.value" :disabled="priceSettingStatus" placeholder="请选择" style="width:100%;" @change="changeMonth($event,index)">
                                                <el-option v-for="item in monthList" :key="item.value" :label="item.name" :value="item.value">
                                                </el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="价格" :prop="'priceSettingList.' + index + '.price'" :rules="[{required: true, message: '价格不能为空', trigger: 'blur'},{ pattern: /^[1-9]\d*$/, message: '请输入正确的价格，价格需大于0元，且为整数', trigger: 'blur'}]">
                                            <el-input v-model="site.price" :disabled="priceSettingStatus" placeholder="请输入价格" :maxlength="4" style="width:100%;"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="6" v-if='index != 0'>
                                        <el-button class="delBtn" type="text" v-if="!priceSettingStatus" @click.prevent="removeDomain(index)"><i class="el-icon-delete"></i></el-button>
                                    </el-col>
                                </el-row>
                            </div>
                            <el-button type="text" @click="addPriceSetting" v-if="!priceSettingStatus && priceSetting.priceSettingList.length<12" class="addBtn"><i class="el-icon-plus"></i> 继续添加</el-button>
                        </el-col>
                    </el-row>
                </div>

                <div class="form-item">
                    <div class="form-item-title">
                        <span class="title-level">活动设置</span>
                    </div>
                    <el-button type="text" @click="addActive" v-if="!activeStatus && !priceSettingStatus" class="addActive"><i class="el-icon-plus"></i> 创建活动</el-button>
                    <el-row class="form-content" v-if="activeStatus">
                        <el-col :span="20">
                            <el-row :gutter="21">
                                <el-col :span="8">
                                    <el-form-item label="活动名称" prop="activityName">
                                        <el-input v-model="priceSetting.activityName" :disabled="priceSettingStatus" placeholder="请输入内容" :maxlength="10" style="width:100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="活动折扣" prop="activityDiscount">
                                        <el-input v-model="priceSetting.activityDiscount" :disabled="priceSettingStatus" placeholder="请输入内容" :maxlength="4" style="width:100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="21">
                                <el-col :span="8">
                                    <el-form-item label="开始日期" prop="startTime">
                                        <el-date-picker v-model="priceSetting.startTime" :editable="false" :disabled="priceSettingStatus" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="选择开始日期" @change="dateChange1" :picker-options="priceSetting.pickerOptions1" style="width:100%"></el-date-picker>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8   ">
                                    <el-form-item label="结束日期" prop="endTime">
                                        <el-date-picker v-model="priceSetting.endTime" :editable="false" :disabled="priceSettingStatus" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="选择结束日期" @change="dateChange2" :picker-options="priceSetting.pickerOptions2" style="width:100%"></el-date-picker>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="6">
                                    <el-button class="delBtn" type="text" :disabled="priceSettingStatus" @click="removeActive"><i class="el-icon-delete"></i></el-button>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </div>

                <div class="form-item">
                    <div class="form-item-title">
                        <span class="title-level">经销商分成设置</span>
                    </div>
                    <el-row class="form-content">
                        <el-col :span="20">
                            <el-row :gutter="21">
                                <el-col :span="8">
                                    <el-form-item label="分成比例" prop="dividedPercentage">
                                        <el-input v-model="priceSetting.dividedPercentage" :disabled="priceSettingStatus" placeholder="请输入内容" :maxlength="4" style="width:100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </div>

                <div class="form-item">
                    <div class="form-item-title">
                        <span class="title-level">服务折扣设置</span>
                    </div>
                    <el-row class="form-content">
                        <el-col :span="20">
                            <el-row :gutter="21">
                                <el-col :span="8">
                                    <el-form-item label="服务折扣" prop="serviceDiscount">
                                        <el-input v-model="priceSetting.serviceDiscount" :disabled="priceSettingStatus" placeholder="请输入内容" :maxlength="4" style="width:100%;"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </div>

                <div class="form-item">
                    <div class="form-item-title">
                        <span class="title-level">会员特权试用设置</span>
                    </div>
                    <el-row class="form-content">
                        <el-col :span="20">
                            <el-row :gutter="21">
                                <el-col :span="8">
                                    <el-form-item label="错题本" prop="wrongCount">
                                        <el-input v-model="priceSetting.wrongCount" :disabled="priceSettingStatus" placeholder="请输入内容" :maxlength="12" style="width:100%;"></el-input>
                                    </el-form-item>
                                    <div class="price-exegesis">错题本错题数量上限</div>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="提分练习" prop="extractCount">
                                        <el-input v-model="priceSetting.extractCount" :disabled="priceSettingStatus" placeholder="请输入内容" :maxlength="12" style="width:100%;"></el-input>
                                    </el-form-item>
                                    <div class="price-exegesis">提分练习试用次数限制</div>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="专项练习" prop="studyCount">
                                        <el-input v-model="priceSetting.studyCount" :disabled="priceSettingStatus" placeholder="请输入内容" :maxlength="12" style="width:100%;"></el-input>
                                    </el-form-item>
                                    <div class="price-exegesis">专项练习试用次数限制</div>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </div>

                <div class="footer">
                    <el-button type="primary" @click="revise('priceSetting')" v-if="priceSettingStatus">修 改</el-button>
                    <el-button type="primary" @click="submitForm('priceSetting')" v-if="!priceSettingStatus">保 存</el-button>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import Levelbar from '../layout/Levelbar';
import { getchargeSetting, updatePriceSetting} from 'api/memberMangement';
import school from 'components/SchoolClasss/school';
import moment from 'moment';

export default {
    name: 'getAttendance',
    components: { Levelbar, school},
    data() {
        var validStart = (rule, value, callback) => {
            if (this.priceSetting.endTime) {
                this.$refs.priceSetting.validateField('endTime');
                callback();
            } else {
                callback();
            }
        };
        var validEnd = (rule, value, callback) => {
            if (this.priceSetting.startTime && value) {
                if (new Date(moment(value).format('YYYY-MM-DD HH:mm')) <= new Date(moment(this.priceSetting.startTime).format('YYYY-MM-DD HH:mm'))) {
                    callback(new Error('结束日期必须大于开始日期'));  
                } else {
                    callback();
                }
            } else {
                callback();   
            }
        };
        return {
            loading: false,
            priceSettingStatus: true,
            activeStatus: false,
            schoolStatus: 3,
            monthList: [
                {
                    name: '请选择',
                    value: ''
                },
                {
                    name: '1个月',
                    value: '1'
                },
                {
                    name: '2个月',
                    value: '2'
                },
                {
                    name: '3个月',
                    value: '3'
                },
                {
                    name: '4个月',
                    value: '4'
                },
                {
                    name: '5个月',
                    value: '5'
                },
                {
                    name: '6个月',
                    value: '6'
                },
                {
                    name: '7个月',
                    value: '7'
                },
                {
                    name: '8个月',
                    value: '8'
                },
                {
                    name: '9个月',
                    value: '9'
                },
                {
                    name: '10个月',
                    value: '10'
                },
                {
                    name: '11个月',
                    value: '11'
                },
                {
                    name: '12个月',
                    value: '12'
                }
            ],
            extractCount: '',
            studyCount: '',
            wrongCount: '',
            priceSetting: {
                activityName: '',
                activityDiscount: '',
                startTime: '',
                endTime: '',
                extractCount: '',
                studyCount: '',
                wrongCount: '',
                pickerOptions1: {},
                pickerOptions2: {},
                dividedPercentage: '',
                serviceDiscount: '',
                priceSettingList: [{
                    name: '',
                    value: '',
                    price: ''
                }]
            },
            chargeId: '', // 设置id
            activityId: '', // 活动id
            priceSettingRules: {
                activityName: [
                    { required: true, message: '内容不能为空', trigger: 'blur' }
                ],
                activityDiscount: [
                    { required: true, message: '内容不能为空', trigger: 'blur' },
                    { pattern: /^0\.[1-9][0-9]{0,1}$/, message: '活动折扣范围0.01～0.99', trigger: 'blur'}
                ],
                startTime: [
                    { required: true, type: 'date', message: '开始日期不能为空', trigger: 'change' },
                    { validator: validStart, trigger: 'change'}
                ],
                endTime: [
                    {required: true, type: 'date', message: '结束日期不能为空', trigger: 'change' },
                    { validator: validEnd, trigger: 'change'}
                ],
                dividedPercentage: [
                    { required: true, message: '内容不能为空', trigger: 'blur' },
                    { pattern: /^0\.[1-9][0-9]{0,1}$/, message: '分成比例范围0.01～0.99', trigger: 'blur'}
                ],
                serviceDiscount: [
                    { required: true, message: '内容不能为空', trigger: 'blur' },
                    { pattern: /^0\.[1-9][0-9]{0,1}$/, message: '服务折扣范围0.01～0.99', trigger: 'blur'}
                ],
                extractCount: [
                        { required: true, message: '内容不能为空', trigger: 'blur' },
                        { pattern: /^(?:0|[1-9][0-9]?|100)$/, message: '请输入0到100之间的整数', trigger: 'change,blur' },
                    { validator: (rule, value, callback) => {
                        if (value && Number(value)<Number(this.extractCount)) {
                            callback(new Error('只能设置比当前值大的整数'));
                        } else {
                            callback();
                        }
                    }, trigger: 'change,blur' }
                ],
                studyCount: [
                        { required: true, message: '内容不能为空', trigger: 'blur' },
                        { pattern: /^(?:0|[1-9][0-9]?|100)$/, message: '请输入0到100之间的整数', trigger: 'change,blur' },
                    { validator: (rule, value, callback) => {
                        if (value && Number(value)<Number(this.studyCount)) {
                            callback(new Error('只能设置比当前值大的整数'));
                        } else {
                            callback();
                        }
                    }, trigger: 'change,blur' }
                ],
                wrongCount: [
                        { required: true, message: '内容不能为空', trigger: 'blur' },
                        { pattern: /^(?:0|[1-9][0-9]?|100)$/, message: '请输入0到100之间的整数', trigger: 'change,blur' },
                    { validator: (rule, value, callback) => {
                        if (value && Number(value)<Number(this.wrongCount)) {
                            callback(new Error('只能设置比当前值大的整数'));
                        } else {
                            callback();
                        }
                    }, trigger: 'change,blur' }
                ]
            }
        };
    },
    created() {
        this.getcharge();
    },
    methods: {
        schoolChange(val) {
            this.dataForm.schoolId = val;
            if (this.schoolStatus != 3) {
                this.queryAllGrade();
            }
        },
         // 开始日期選擇
        dateChange1(date) {
            this.priceSetting.pickerOptions2 = {
                disabledDate(time) {
                    return time.getTime() < new Date(date).getTime() -864e5;
                }
            }
        },
        // 结束日期选择
        dateChange2(date) {
            this.priceSetting.pickerOptions1 = {
                disabledDate(time) {
                    return time.getTime() > new Date(date).getTime() - 864e5;
                }
            }
        },
        addActive() {
            this.activeStatus = true;
        },
        removeActive() {
            this.$confirm('是否确认删除?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.activeStatus = false;
                this.activityId = '';
                this.priceSetting.activityName = '';
                this.priceSetting.activityDiscount = '';
                this.priceSetting.startTime = '';
                this.priceSetting.endTime = '';
            })
        },
        getcharge() {
            this.loading = true;
            getchargeSetting().then(res => {
                this.loading = false;
                if (res.data.content.chargeId===null) {
                    this.chargeId = '';
                    this.priceSettingStatus = false;
                    this.priceSetting.dividedPercentage = '';
                    this.priceSetting.serviceDiscount = '';
                    this.priceSetting.priceSettingList = [
                        {
                            value: '',
                            name: '',
                            price: ''
                        }
                    ]
                } else {
                    this.priceSettingStatus = true;
                    this.chargeId = res.data.content.chargeId;
                    this.priceSetting.priceSettingList = JSON.parse(res.data.content.chargeDetail);
                    this.priceSetting.dividedPercentage = res.data.content.dividedPercentage;
                    this.priceSetting.serviceDiscount = res.data.content.serviceDiscount;
                    this.priceSetting.extractCount = String(res.data.content.extractCount);
                    this.priceSetting.studyCount = String(res.data.content.studyCount);
                    this.priceSetting.wrongCount = String(res.data.content.wrongCount);
                    this.extractCount = res.data.content.extractCount;
                    this.studyCount = res.data.content.studyCount;
                    this.wrongCount = res.data.content.wrongCount;
                }
                if (res.data.content.activityId===null) {
                    this.activityId = '';
                    this.activeStatus = false;
                    this.priceSetting.activityName = '';
                    this.priceSetting.activityDiscount = '';
                    this.priceSetting.startTime = '';
                    this.priceSetting.endTime = '';
                } else {
                    this.activityId = res.data.content.activityId;
                    this.activeStatus = true;
                    this.priceSetting.activityName = res.data.content.activityName;
                    this.priceSetting.activityDiscount = res.data.content.activityDiscount;
                    this.priceSetting.startTime = new Date(res.data.content.startTime);
                    this.priceSetting.endTime = new Date(res.data.content.endTime);
                }
            })
        },
        changeMonth(val, index) {
            this.priceSetting.priceSettingList[index].name = this.monthList.find(item => {
                return val == item.value;
            }).name;
            let monthList = this.priceSetting.priceSettingList.map((item) => {
                return item.value
            })
            let newList = monthList.splice(index, 1);
            if (monthList.includes(newList[0]) && newList[0] != '') {
                this.$message.error('您选择的月份重复，请重新选择');
            }
        },
        revise(dataForm) {
            if (dataForm=='priceSetting') {
                this.priceSettingStatus = false;
            }
        },
        submitForm(dataForm) {
            this.$refs[dataForm].validate(valid => {
                if (valid) {
                    let monthList = this.priceSetting.priceSettingList.map((item) => {
                        return item.value
                    })
                    for (var i = 0; i<monthList.length; i++) {
                        let monthListCopy = [...monthList];
                        let newList = monthListCopy.splice(i, 1);
                        if (monthListCopy.includes(newList[0])) {
                            this.$message.error('您选择的月份重复，请重新选择');
                            return;
                        }
                    }
                    this.$confirm('确定要保存信息吗?', ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        let priceSettingListJson = JSON.stringify(this.priceSetting.priceSettingList)
                        let startDate = this.priceSetting.startTime==''?'':moment(this.priceSetting.startTime).format('YYYY-MM-DD HH:mm');
                        let endDate = this.priceSetting.endTime==''?'':moment(this.priceSetting.endTime).format('YYYY-MM-DD HH:mm');
                        updatePriceSetting(this.chargeId, this.activityId, priceSettingListJson, this.priceSetting.activityName, 
                        this.priceSetting.activityDiscount, startDate, endDate, 
                        this.priceSetting.dividedPercentage, this.priceSetting.serviceDiscount, this.priceSetting.wrongCount, this.priceSetting.extractCount,
                        this.priceSetting.studyCount).then(res => {
                            this.$message.success('保存成功');
                            this.getcharge();
                        })
                    })
                } 
            });
        },
        addPriceSetting() {
            if (this.priceSetting.priceSettingList.length > 11) {
                this.$message({
                    type: 'warning',
                    message: '价格设置最多添加12个'
                })
                return '';
            }
            let monthObj = {
                value: '',
                name: '',
                price: ''
            };
            this.priceSetting.priceSettingList.push(monthObj)
        },
        removeDomain(index) {
            this.$confirm('是否确认删除?', ' ', {
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.priceSetting.priceSettingList.splice(index, 1);
            })
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.app-container {
  position: relative;
  padding: 20px 20px 10px;
  $bgcolor: #fff;

  @mixin showTitle() {
    background: $bgcolor;
    box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
    -webkit-box-shadow:  0px 0px 5px 0px rgba(0, 0, 0, 0.1);
  }
  .form-box {
    padding: 0 50px;
    @include showTitle();
    .form-title {
      padding-top:8px;
      text-align: center;
      font-size: 18px;
      color: #333;
      line-height: 72px;
      font-weight: bold;
      font-family: Microsoft YaHei;
      border-bottom: 1px solid #ddd;
    }
    .addBtn{
        margin:0px 0 0px 12px;
        font-size: 14px;
        color: #ff5e2c;
    }
    .addActive{
        margin:0px 0 0px 20px;
        font-size: 14px;
        color: #ff5e2c;
    }
    .delBtn {
        font-size: 20px;
        color:#999;
        margin-left:30px;
    }
    .form {
      .form-item {
        padding-bottom: 40px;
        .form-item-title {
            margin: 40px 0;
            font-size: 14px;
            color: #333;
            line-height: 14px;
            border-left: 4px solid #ff5e2c;
            text-indent: 16px;
        }
        .form-content {
            margin: 0 8px;
        }
      }
    .footer{
        text-align: center;
        padding-bottom:50px;
    }
    }
  }
  .price-exegesis{
      color: #999999;
      padding-left:80px;
      font-size: 14px;
  }
}
</style>